/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hanze.shoestring.dao.impl;

import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import javax.persistence.metamodel.EntityType;
import nl.hanze.shoestring.dao.PersoonDAO;
import nl.hanze.shoestring.domain.Persoon;
import nl.hanze.shoestring.domain.Persoon_;

/**
 *
 * @author alex
 */
public class PersoonDAOImpl extends BaseDAOImpl<Persoon> implements PersoonDAO {

    public PersoonDAOImpl() {
    }

    public List<Persoon> find(String name) {
        boolean hasName = name != null && name.length() > 0;

        if (!hasName) {
            return getAll();
        }

        open();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Persoon> query = cb.createQuery(Persoon.class);
        Root<Persoon> persoon = query.from(Persoon.class);

        Predicate p = cb.or(cb.like(persoon.get(Persoon_.achternaam), name + "%"), cb.like(persoon.get(Persoon_.voornaam), name + "%"),
                cb.like(persoon.get(Persoon_.email), "%" + name + "%"));

        query.where(p);

        TypedQuery<Persoon> typedQuery = em.createQuery(query);
        return typedQuery.getResultList();
    }

}
